package action;

import bean.Reader;
import bean.Users;
import dao.ReaderDAO;
import dao.UserDAO;

import java.util.List;

/**
 * Created by WeaponLin on 2015/11/14.
 */
public class LoginAction extends SuperAction{

    public String login() {
        UserDAO uDao = new UserDAO();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Users user = uDao.usersLogin(username,
                password);

        if (formVerify(user)) {
            session.setAttribute("loginName", user.getUsername());//设置登录名
            session.setAttribute("loginState", 1); //设置登录状态

            if (user.getState() == 1) {  //登录用户为管理员
                session.setAttribute("isAdmin", true);
                return "adminLogin_succ";
            }
            else {   //登录用户为读者
                ReaderDAO readerDAO = new ReaderDAO();
                List<Reader> reader = readerDAO.queryReaderBySql("readerid='"+user.getUsername()+"'");
                if(reader.size() > 0){
                    if(reader.get(0).getIsloss().equals("是")){
                        this.addFieldError("lossError", "读者证处于挂失状态，无法登录系统！");
                        return "login_fail";
                    }

                    session.setAttribute("reader",reader.get(0));
                }
                else
                    session.setAttribute("reader",null);
                session.setAttribute("isAdmin", false);
                return "userLogin_succ";
            }
        }
        return "login_fail";
    }

    public String logout() {
        if (session.getAttribute("loginName") != null) {
            session.setAttribute("loginState", 0);
            session.removeAttribute("loginName");
            session.removeAttribute("isAdmin");
        }
        return "logout_succ";
    }

    private boolean formVerify(Users user) {
        if (user == null) {
            this.addFieldError("loginError", "用户名或密码错误");
            return false;
        }
        return true;
    }
}
